package com.itheima.health.config;

import com.itheima.health.pojo.Permission;
import com.itheima.health.pojo.Role;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @Author: liangWeiQUQ
 * @Description: 权限配置类---->加载用户权限配置类
 * @DateTime: 2021/3/8 11:39
 **/
@Component
public class CustomerUserDetail implements UserDetailsService {
    @DubboReference
    private UserService userService;

    /**
     * @Author: 传闻中的梁大侠
     * @Date: 11:40 2021/3/8
     * @Parms [s]
     * @ReturnType: org.springframework.security.core.userdetails.UserDetails
     * @Description: 用户权限配置类
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据姓名查询用户的信息
        User user = userService.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("查询无此用户，请您核实后在操作");
        }

        StringBuffer authStr = new StringBuffer();
        Set<Role> roles = user.getRoles();
        //遍历角色
        for (Role role : roles) {
            authStr.append(role.getKeyword());
            authStr.append(",");

            //获取权限
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                authStr.append(permission.getKeyword());
                authStr.append(",");
            }
        }

        if (authStr.length() > 0) {
            authStr.deleteCharAt(authStr.length() - 1);
        }
        return new org.springframework.security.core.userdetails.User(username, user.getPassword(),
                                    AuthorityUtils.commaSeparatedStringToAuthorityList(authStr.toString()));
    }
}
